<?php

namespace app\widgets;

use app\extensions\weixin\WeiXin;
use yii\base\Widget;
use yii\helpers\Json;
use yii\web\View;

class WxJsWidget extends Widget {

    public function run() {
        $this->view->registerJsFile('http://res.wx.qq.com/open/js/jweixin-1.2.0.js', ['position' => View::POS_BEGIN]);

        /* @var $wx WeiXin */
        $wx = \Yii::$app->get('weixin');

        $data = $wx->getSignPackage();
        $data['debug'] = 'false';
        if (!isset($data['appId'])) {
            return;
        }

        $js = $this->getClient($data);
        $this->view->registerJs($js, View::POS_BEGIN);
    }

    protected function getClient($data) {
        $options = <<<EOF
        
    wx.config({
        debug: {$data['debug']},
        appId: '{$data['appId']}',
        timestamp: {$data['timestamp']},
        nonceStr: '{$data['nonceStr']}',
        signature: '{$data['signature']}',
        jsApiList: [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onRecordEnd',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard'
        ]
    });
    wx.error(function (res) {
        alert(res);
    });
EOF;
        return $options;
    }
}